package com.cyt.sys.interceptor;

import com.alibaba.fastjson.JSON;
import com.cyt.base.model.dto.ReturnResult;
import com.cyt.base.util.StringUtils;
import com.cyt.sys.model.po.SysUserToken;
import com.cyt.sys.service.SysUserTokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *  token拦截器
 *
 * @author congcong tao
 * @create 2019/4/24 8:22
 */
public class TokenInterceptor extends HandlerInterceptorAdapter{

    @Autowired
    private SysUserTokenService sysUserTokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求token，如果token不存在，直接返回401
        String token = getRequestToken(request);
        if (StringUtils.isBlank(token)) {
            HttpServletResponse httpResponse = response;
            String json = JSON.toJSONString(new ReturnResult(401, "invalid token"));
            httpResponse.getWriter().print(json);
            return false;
        }
        SysUserToken sysUserToken = sysUserTokenService.selectByToken(token);
        if (sysUserToken == null) {
            HttpServletResponse httpResponse = response;
            String json = JSON.toJSONString(new ReturnResult(401, "invalid token"));
            httpResponse.getWriter().print(json);
            return false;
        }
        // token失效
        if(sysUserToken == null || sysUserToken.getExpireTime().getTime() < System.currentTimeMillis()){
            HttpServletResponse httpResponse = response;
            String json = JSON.toJSONString(new ReturnResult(401, "token失效，请重新登录"));
            httpResponse.getWriter().print(json);
            return false;
        }
        return true;
    }

    /**
     * 获取请求的token
     */
    private String getRequestToken(HttpServletRequest httpRequest){
        // 从header中获取token
        String token = httpRequest.getHeader("token");
        // 如果header中不存在token，则从参数中获取token
        if (StringUtils.isBlank(token)) {
            token = httpRequest.getParameter("token");
        }
        return token;
    }
}
